#version 330
uniform vec3 lightIntensity;

uniform sampler2D texture;
uniform sampler2D normalTexture;
uniform sampler2D specularTexture;
uniform sampler2D transparencyTexture;

uniform vec3 lightPosition;
uniform vec2 lightMode;
uniform vec2 selected;
uniform vec3 cameraPosition;

in vec3 coords;
in vec2 texCoord;
in mat3 tangentMatrix;
in vec4 shadowCoord;
in float zPos;

layout( location = 0 ) out vec4 fragColor;

void main() {
    vec4 textureColor = texture2D(texture,texCoord.xy);
    vec4 transparency = texture2D(transparencyTexture,texCoord);
    if(lightMode.x == 1.0) {
        if(lightMode.y == 1.0) fragColor = textureColor;
        else if(transparency.a != 0) fragColor = vec4(0.0,0.0,0.0,1.0);
        if(transparency.a < 0.2) discard;
    } else if(selected.x == 1.0) {
        if(selected.y == 1.0) fragColor += vec4(0.0,0.8,0.8,1.0);
        else fragColor = vec4(0.0,0.0,0.0,0.0);
    } else {
        if(transparency.a < 0.2) discard;
        else {
            if(lightMode.y == 1.0) {
                fragColor = textureColor;
            } else {
                vec4 normalT = normalize(2.0*texture2D(normalTexture,texCoord)-vec4(1.0));

                vec3 dayS = normalize(lightPosition - coords);
                vec3 nightS = normalize(coords - lightPosition);
                vec3 dayLightDir = normalize(tangentMatrix * dayS);
                vec3 nightLightDir = normalize(tangentMatrix * nightS);

                vec3 diffuse = vec3(2.0 - (1.0 - dot(dayLightDir,normalT)));

                float specular = 0.0;
                if(diffuse == vec3(0.0)) {
                    dayS = normalize(coords - lightPosition);
                    dayLightDir = normalize(tangentMatrix * dayS);
                    diffuse = vec3(max(dot(dayLightDir,normalT),0.0)) * 0.25;
                } else {
                    vec3 vertexToCam = normalize(cameraPosition - coords);
                    vec3 r = reflect(dayLightDir,normalT);
                    float specularFactor = dot(vertexToCam, r);
                    specularFactor = pow(specularFactor,10.0);
                    if(specularFactor > 0.0)
                        specular = specularFactor * texture2D(specularTexture,texCoord).a;
                }
                vec4 specularColor = textureColor * specular;

                vec4 diffuesColor = textureColor * (vec4(lightIntensity * diffuse,1.0 ).x);


                vec4 ambientColor = textureColor;
                fragColor = diffuesColor + ambientColor + vec4(specularColor.rgb,1.0);
                fragColor = fragColor * transparency.a;
            }
        }
    }
}
